var url = require('url');
const axios = require('axios');
const express = require('express');
const { Worker, isMainThread } = require('worker_threads');

var app = express();
axios.defaults.withCredentials = true;

function json2post(params) { //把json参数转化为普通post参数
    let param = '';
    for (let key in params) {
        param += '&' + key + '=' + params[key]
    }
    return param.replace('&', '');
}

async function request_data(params) { //请求函数
    //网址匹配表达式
    let reg = /^(?:(http|https|ftp):\/\/)?((?:[\w-]+\.)+[a-z0-9]+)((?:\/[^/?#]*)+)?(\?[^#]+)?(#.+)?$/i;
    let {
        url,
        method,
        data,
        cookies
    } = params;
    let headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
    };
    if (cookies) {
        headers['cookie'] = cookies;
    }
    if (reg.test(url)) {
        if (method.toUpperCase() == 'GET') {
            return axios.get(url, {
                headers: headers
            })
        } else if (method.toUpperCase() == 'POST') {
            return axios.post(url, json2post(data), {
                headers: headers
            })
        }
    }
    return {
        data: '请输入正确的数据格式'
    };
}


app.get('*', function (req, res) {
    let worker = new Worker("./ityxb.js")
    worker.on('message',message => {
        res.send(message);
    })
    res.send("get")
})
app.use(express.json())
app.use(express.urlencoded({
    extended: false
}))
app.post('*', function (req, res) {
    //设置跨域
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header('Access-Control-Allow-Credentials', true);

    if (req.body.url && req.body.method) {
        request_data(req.body).then(function (response) {
            console.log(response);
            if (response.headers['set-cookie']) {
                res.header('Set-Cookie', response.headers['set-cookie'])
            }
            res.send(response.data);
        })
    } else {
        res.send("请输入正确的数据")
    }
})


var server = app.listen(9001, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("应用实例，访问地址为 http://%s:%s", host, port)
})